import React from "react";
import BaseScreen from "../BaseScreen";
import ProgressView from "../../view/ProgressView";
import { Actions, NameSpace } from "../../model/taskModel";
import { connect } from "react-redux";
import styles from "../../css/attendance.module.css";
import { locationTo, back } from "../../utils/LocationUtil";
import * as locations from '../../const/locations'
import { MyButton } from "../../view/MyButton";
import Config from "../../Config";
import { AVATAR } from "../../const/imgs"
import { HintDialog } from '../../view/Dialog'
import { applyList, cancelApply, } from '../../service/AttendService'
import { getTOKEN, getInfo, setInfo } from "../../utils/StorageUtil";
import { NOTASK } from '../components/Default'
import Scroll from '../components/Bscroll/index'
class ApplyRecords extends BaseScreen {
  constructor(props) {
    super(props);
    this.CURRENT_PAGE = 1;
    this.PER_PAGE = 20;
    this.state = {
      recordList: [],
      loading: false,
      applyTabIndex:0
    };
  }

  getStatus = (e) => {
    let status
    switch (e) {
      case 0:
        status = 2;
        break;
      case 1:
        status = 1;
        break;
      case 2:
        status = 3;
        break;
      case 3:
        status = 4;
        break;
      default:
        status = 2;
      break;
    }
    return status
  }
  // 切换tab  
  switchTab = (e) => {
    // const { applyTabIndex } = this.props    
    console.log(e)

    this.props.applyTab(e)
    this.CURRENT_PAGE = 1
    this.setState({
      recordList: []
    })
    this.getRecords({
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE,
      apply_status: e?this.getStatus(e):2,
      isReFresh: true
    })
  }
  componentDidMount() {
    document.title = '申请记录'
    const { applyTabIndex } = this.props
    this.CURRENT_PAGE = 1

    this.getRecords({
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE,
      apply_status: applyTabIndex?this.getStatus(applyTabIndex):2,
    })
  }
  // 加载申请记录列表
  getRecords = (params) => {
    const recordList = params.isReFresh ? [] : this.state.recordList
    this.setState({ loading: true });
    applyList({
      token: getTOKEN(),
      ...params
    })
      .then(
        res => {
          this.setState({ loading: false });
          if (res.error_code === 0) {
            this.setState({
              recordList: [...recordList, ...res.data]
            })
            this.CURRENT_PAGE++
          }
        }
      )
      .catch(
        err => {
          console.log(err)
        }
      )
  }
  // 下拉加载
  pullingUp = () => {
    const { applyTabIndex } = this.props
    this.getRecords({
      current_page: this.CURRENT_PAGE,
      per_page: this.PER_PAGE,
      apply_status: applyTabIndex?this.getStatus(applyTabIndex):2,
    })
  }
  // 是否取消
  IsCancel = (e, id, type) => {
    e.stopPropagation()

    this.showMsgDialog("你确定要放弃申请吗")
    this.setState({
      canselId: id,
      canselType: type
    })
  }
  // 取消
  cancel = () => {
    this.setState({ loading: true });
    cancelApply({
      token: getTOKEN(),
      apply_type: this.state.canselType,
      id: this.state.canselId
    })
      .then(
        res => {
          this.setState({ loading: false });

          if (res.error_code === 0) {
            this.refs.summit.setState({
              content: '取消成功',
              visibility: true
            });

          }
        }
      )
      .catch(
        err => {
          console.log(err)
        }
      )
  }
  // 详情
  navigate = (id, type) => {
    this.props.setRecordId({
      id: id, type: type
    })
    setInfo('RecordInfo', {
      id: id, type: type
    })
    locationTo(locations.APPLY_DETAIL)
  }
  render() {
    const { applyTabIndex } = this.props
    const { recordList, loading } = this.state
    return (
      <div className={styles["homes"]} style={{ paddingTop: '0' }}>
        <div className={styles['nav_wrapper']}>
          <Navigator click={this.switchTab} selectedIndex={applyTabIndex} />
        </div>
        <div className={styles["wrapper"]}>
          <div className={styles["container"]}>
            <Scroll
              ref='scroll'
              click={true}
              bounce={true}
              pullUpLoad={true}
              pullUpLoadMoreData={this.pullingUp}
              isPullUpTipHide={true}
              isShowMore={this.state.isShowMore}
            >
              {recordList.length === 0 && <NOTASK des='暂无记录~' />}

              <div className={styles['attend_container']}>
                {
                  recordList.map((item, index) => {
                    return (
                      <RecordItem
                        key={index}
                        cancel={this.IsCancel}
                        navigate={this.navigate}
                        item={item}
                      />
                    )
                  })

                }
              </div>
            </Scroll>
          </div>
        </div>
        <HintDialog
          ref="dialog"
          style={{
            color: "#fff"
          }}
          visibility={this.state.alertMsg !== ""}
          content={this.state.alertMsg}
          operateText="确定"
          operateClick={this.cancel}
        />
        <HintDialog
          ref="summit"
          style={{
            color: "#fff"
          }}
          visibility={this.state.alertMsg !== ""}
          content={this.state.alertMsg}
          operateText="确定"
          operateClick={() => { back() }}
        />
        <ProgressView visibility={loading} mode={ProgressView.MODE_MEDIUM} />
      </div>
    )
  }
}
const RecordItem = ({ cancel, navigate, item }) => {
  const { id, type, comment, status } = item
  return (
    <div className={styles['stat_item_w']} style={{ height: '75px' }}>
      <div className={styles['stat_item_borderBottom']}
        onClick={() => navigate(id, type)}
      >
        <div>
          <div className={styles['record_info']}>
            <div className={styles['record_avatar']}>
              <img src={parseInt(getInfo('UserInfo').sex, 10) === 1 ? AVATAR.male : AVATAR.famale} alt='' />
            </div>
            <div style={{ display: 'block' }}>
              <div className={styles['stat_item_key']}>
                {parseInt(type, 10) === 1 && '请假申请'}
                {parseInt(type, 10) === 2 && '补卡申请'}
              </div>
              <div className={styles['stat_item_value']}>
                <div style={{ maxWidth: '240px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  原因：{comment}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className={styles['record_state']}>
          {parseInt(status, 10) === 2 &&
            <MyButton
              style={buttonStyle}
              name={"取消申请"}
              onClick={(e) =>
                cancel(e, id, type)
              }
            />
          }
          {parseInt(status, 10) !==2 &&
            <div className={styles['stat_item_value']}>
              {parseInt(status, 10) === 1 && '已同意'}
              {parseInt(status, 10) === 3 && '已拒绝'}
              {parseInt(status, 10) === 4 && '已取消'}
            </div>
          }
        </div>
      </div>
    </div>
  )
}
const buttonStyle = {
  color: "#fff",
  background: Config.BaseColor,
  fontSize: '13px',
  paddingLeft: '12px',
  paddingRight: '12px',
}
const Navigator = ({ click, selectedIndex }) => {
  return (
    <div className={styles['apply_tabs']}>
      {
        navList.map((item, index) => {
          return (<div
            key={item.name}
            onClick={() => { click(index) }}
            className={styles['apply_nav_item']}
            style={selectedIndex === index ? selectedStyle : {}}
          >
            {item.name}
          </div>)
        })
      }
    </div>
  )
}


const navList = [{
  name: '审批中'
},
{
  name: '已同意'
},
{
  name: '已拒绝'
},
{
  name: '已取消'
}]
const selectedStyle = {
  color: Config.BaseColor,
  borderColor: Config.BaseColor
}
const mapStateToProps = state => {
  return {
    ...state[NameSpace]
  };
};

const mapDispatchToProps = dispatch => {
  return {
    applyTab(applyTabIndex) {
      let params = {
        applyTabIndex: applyTabIndex
      };
      dispatch(Actions.actionApplyTab(params));
    },
    setRecordId({ id, type }) {
      let params = {
        recordId: id,
        recordType: type
      };
      dispatch(Actions.actionSetRecordId(params));
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(ApplyRecords);
// export default ApplyRecords